/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui.table;

import com.camachosanchez.bean.InsumosDespinche;
import com.camachosanchez.gui.textfield.MaxLengthTextDocument;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.GUIUtil;
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Collections;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author ZULLY
 */
public class TablaDespinches extends javax.swing.JPanel implements FocusListener {

    private DefaultTableModel dm;
    private JTextField textCantidad;
    private JTextField textCostoUnit;
    public List<InsumosDespinche> insumosObject;
//    private DecimalFormat formateador;
    public double total = 0;

    /**
     * Creates new form TablaDespinches
     */
    public TablaDespinches() {
        initComponents();
        textCantidad = new JTextField();
        textCantidad.setHorizontalAlignment(JTextField.RIGHT);
        MaxLengthTextDocument docCantidad = new MaxLengthTextDocument();
        docCantidad.setMaxChars(3, Constantes.ENTEROS);
        textCantidad.setDocument(docCantidad);

        textCostoUnit = new JTextField();
        textCostoUnit.setHorizontalAlignment(JTextField.RIGHT);
        MaxLengthTextDocument docCostoUnit = new MaxLengthTextDocument();
        docCostoUnit.setMaxChars(10, Constantes.DECIMALES);
        textCostoUnit.setDocument(docCostoUnit);

        tblDespinche.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        dm = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int col) {
                if (col == 1 || col == 4) {
                    return false;
                }
                return true;
            }

            @Override
            public Class getColumnClass(int c) {
                return String.class;
            }
        };

//        formateador = new DecimalFormat("0.00");

        Object[] columns = new Object[]{"INSUMO", "CÓDIGO", "CANTIDAD", "COSTO UNITARIO", "COSTO TOTAL"};
        dm.setColumnIdentifiers(columns);
        tblDespinche.setModel(dm);
        tblDespinche.setFillsViewportHeight(true);
        tblDespinche.setRowHeight(20);

        tblDespinche.getTableHeader().setReorderingAllowed(false);

        RenderizadorTablaDespinches render = new RenderizadorTablaDespinches(tblDespinche.getTableHeader().getDefaultRenderer());
        tblDespinche.setDefaultRenderer(Object.class, render);

        tblDespinche.getModel().addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {
                if (insumosObject != null) {
                    if (e.getColumn() == 0) {
                        String nombreInsumo = dm.getValueAt(e.getFirstRow(), 0).toString();
                        int index = Collections.binarySearch(insumosObject, new InsumosDespinche(Short.valueOf("0"), 0, nombreInsumo, true));
                        if (index >= 0) {
                            int codigo = insumosObject.get(index).getCodigo();
                            dm.setValueAt(codigo, e.getFirstRow(), 1);
                        }
                    } else if (e.getColumn() == 3 || e.getColumn() == 2) {
                        if (!dm.getValueAt(e.getFirstRow(), 2).equals("") && !dm.getValueAt(e.getFirstRow(), 3).equals("")) {
                            int cantidad = Integer.parseInt(dm.getValueAt(e.getFirstRow(), 2).toString());
                            double precio = Double.parseDouble(dm.getValueAt(e.getFirstRow(), 3).toString());
                            dm.setValueAt(GUIUtil.formatearNumero(precio * cantidad), e.getFirstRow(), 4);
                        } else {
                            dm.setValueAt("0.00", e.getFirstRow(), 4);
                        }

                    } else if (e.getColumn() == 4) {
                        total = 0;
                        for (int i = 0; i < dm.getRowCount(); i++) {
                            total += Double.parseDouble(dm.getValueAt(i, 4).toString());
                        }
                        txtTotal.setText(GUIUtil.formatearNumero(total));
                    }
                }
            }
        });

        establecerEventosTeclas();
        DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) tblDespinche.getTableHeader().getDefaultRenderer();
        renderer.setHorizontalAlignment(JLabel.CENTER);
    }

    public void setAnchoColumnas() {
        GUIUtil.SetAnchoColumnas(tblDespinche);
//        int anchoColumna = 0;
//        TableColumnModel modeloColumna = tblDespinche.getColumnModel();
//        TableColumn columnaTabla;
//        for (int i = 0; i < tblDespinche.getColumnCount(); i++) {
//            columnaTabla = modeloColumna.getColumn(i);
//            switch (i) {
//                case 0:
//                    anchoColumna = 260;
//                    break;
//                case 1:
//                    anchoColumna = 90;
//                    break;
//                case 2:
//                    anchoColumna = 70;
//                    break;
//                case 3:
//                case 4:
//                    anchoColumna = 100;
//            }
//            columnaTabla.setMinWidth(anchoColumna);
//            columnaTabla.setMaxWidth(anchoColumna);
//            columnaTabla.setPreferredWidth(anchoColumna);
//        }
    }

    private void establecerEventosTeclas() {
        TableColumn columnaCantidad = tblDespinche.getColumnModel().getColumn(2);
        textCantidad.addFocusListener(this);
        textCantidad.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 4));
        DefaultCellEditor singleclickCantidad = new DefaultCellEditor(textCantidad);
        singleclickCantidad.setClickCountToStart(1);
        columnaCantidad.setCellEditor(singleclickCantidad);

        TableColumn columnaCostoUnit = tblDespinche.getColumnModel().getColumn(3);
        textCostoUnit.addFocusListener(this);
        textCostoUnit.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 4));
        DefaultCellEditor singleclickCostoUnit = new DefaultCellEditor(textCostoUnit);
        singleclickCostoUnit.setClickCountToStart(1);
        columnaCostoUnit.setCellEditor(singleclickCostoUnit);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollTabla = new javax.swing.JScrollPane();
        tblDespinche = new javax.swing.JTable();
        pnlPrecioTotal = new javax.swing.JPanel();
        lblTotal = new javax.swing.JLabel();
        lblEmpty = new javax.swing.JLabel();
        txtTotal = new javax.swing.JTextField();

        setLayout(new java.awt.BorderLayout());

        scrollTabla.setBackground(new java.awt.Color(255, 255, 255));

        tblDespinche.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblDespinche.setRowHeight(22);
        scrollTabla.setViewportView(tblDespinche);

        add(scrollTabla, java.awt.BorderLayout.CENTER);

        pnlPrecioTotal.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 0, 5));

        lblTotal.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblTotal.setText("Total:");
        pnlPrecioTotal.add(lblTotal);

        lblEmpty.setText("   ");
        pnlPrecioTotal.add(lblEmpty);

        txtTotal.setEditable(false);
        txtTotal.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtTotal.setText("0.00");
        txtTotal.setPreferredSize(new java.awt.Dimension(100, 20));
        pnlPrecioTotal.add(txtTotal);

        add(pnlPrecioTotal, java.awt.BorderLayout.PAGE_END);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel lblEmpty;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JPanel pnlPrecioTotal;
    private javax.swing.JScrollPane scrollTabla;
    private javax.swing.JTable tblDespinche;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables

    @Override
    public void focusGained(FocusEvent e) {
        if (e.getSource() == textCantidad) {
            textCantidad.setBackground(new Color(255, 251, 170));
            textCantidad.requestFocusInWindow();
            textCantidad.setEditable(true);
            textCantidad.selectAll();
        } else if (e.getSource() == textCostoUnit) {
            textCostoUnit.setBackground(new Color(255, 251, 170));
            textCostoUnit.requestFocusInWindow();
            textCostoUnit.setEditable(true);
            textCostoUnit.selectAll();
        }
    }

    @Override
    public void focusLost(FocusEvent e) {
    }

    public void addRow(Object[] data) {
        if (tblDespinche.getCellEditor() != null) {
            tblDespinche.getCellEditor().stopCellEditing();
        }
        dm.addRow(data);
    }

    public void deleteRow() {
        if (tblDespinche.getCellEditor() != null) {
            tblDespinche.getCellEditor().stopCellEditing();
        }
        int fila = tblDespinche.getSelectedRow();
        if (fila > -1) {
            dm.removeRow(fila);
        }
    }

    public DefaultTableModel getData() {
        return dm;
    }

    public void limpiarTabla() {
        dm.setRowCount(0);
    }

    public void cancelarEdicionCelda() {
        if (tblDespinche.getCellEditor() != null) {
            tblDespinche.getCellEditor().stopCellEditing();
        }
    }

    public TableColumn getColumnModel(int columna) {
        TableColumn col = tblDespinche.getColumnModel().getColumn(columna);
        return col;
    }
}
